import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

abstract class BasePlatformView<T extends BasePlatformViewController>
    extends StatefulWidget {
  final Function onPlatformViewCreatedCallback;
  final dynamic creationParams;

  BasePlatformView(
      {Key key, this.onPlatformViewCreatedCallback, this.creationParams})
      : super(key: key);

  String viewType();

  T createPlatformViewController(String viewType, int id);

  void initState() {}

  @override
  State<StatefulWidget> createState() => _BasePlatformViewState();
}

class _BasePlatformViewState extends State<BasePlatformView> {
  @override
  void initState() {
    super.initState();
    widget.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return AndroidView(
        viewType: widget.viewType(),
        creationParams: widget.creationParams,
        creationParamsCodec: const StandardMessageCodec(),
        onPlatformViewCreated: (int id) {
          _onPlatformViewCreated(id, widget.viewType());
        },
      );
    } else if (defaultTargetPlatform == TargetPlatform.iOS) {
      return UiKitView(
        viewType: widget.viewType(),
        creationParams: widget.creationParams,
        creationParamsCodec: const StandardMessageCodec(),
        onPlatformViewCreated: (int id) {
          _onPlatformViewCreated(id, widget.viewType());
        },
      );
    }
    return Text(
        '$defaultTargetPlatform is not yet supported by the text_view plugin');
  }

  void _onPlatformViewCreated(int id, String viewType) {
    if (widget.onPlatformViewCreatedCallback == null) {
      return;
    }
    widget.onPlatformViewCreatedCallback(
        widget.createPlatformViewController(viewType, id));
  }

  @override
  void dispose() {
    super.dispose();
    // print("flutter-BasePlatformView释放");
  }
}

class NativePlatformViewChannel {
  NativePlatformViewChannel._(String viewType, int id)
      : _channel = new MethodChannel('$viewType' + '_' + '$id');
  final MethodChannel _channel;

  Future<void> invokeMethod(String method, dynamic params) async {
    assert(params != null);
    return _channel.invokeMethod(method, params);
  }

  void setMethodCallHandler(Future<dynamic> handle(MethodCall call)) {
    _channel.setMethodCallHandler(handle);
  }
}

class BasePlatformViewController {
  NativePlatformViewChannel nativePlatformViewChannel;

  BasePlatformViewController(String viewType, int id) {
    nativePlatformViewChannel = NativePlatformViewChannel._(viewType, id);
  }
}
